﻿using EMoney.IStock.OAuth.DataAccess;
using EMoney.IStock.OAuth.Framework;
using EMoney.IStock.OAuth.Models;
using QConnectSDK;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EMoney.IStock.OAuth.Business
{
    public class OAuthBll
    {
        //private const string USERID_MEMCACHED_KEY = "EMoney.IStock.OAuth.Business.OAuthBll.UserID";
        private const string OPENID_CACHED_KEY = "EMoney.IStock.Client.Business.JRPT.OAuthBll.OpenID";
        private const string USERQQ_CACHED_KEY = "EMoney.IStock.Client.Business.JRPT.OAuthBll.UserQQ";

        /// <summary>
        /// 获取联合登录结果
        /// </summary>
        /// <param name="reqLogin"></param>
        /// <returns></returns>
        public LoginResult GetLoginResult(ReqLogin reqLogin)
        {
            LoginResult loginResult = null;

            try
            {
                if (reqLogin != null && !string.IsNullOrEmpty(reqLogin.account))
                {
                    int retValue = 0;
                    string retMsg = string.Empty;
                    string thirdID = string.Empty;
                    string thirdUrl = string.Empty;
                    string thirdNickname = string.Empty;

                    switch ((RegLoginType)reqLogin.userType)
                    {
                        case RegLoginType.QQ:
                            QOpenClient qzone = null;

                            if (!string.IsNullOrEmpty(reqLogin.os) && !string.IsNullOrEmpty(reqLogin.dn))
                            {
                                qzone = new QOpenClient(new QConnectSDK.Models.OAuthToken()
                                {
                                    AccessToken = reqLogin.md5,
                                    OpenId = reqLogin.account
                                });
                            }
                            else
                            {
                                qzone = new QOpenClient(reqLogin.account, string.Empty);
                            }

                            var currentUser = qzone.GetCurrentUser();
                            currentUser.Figureurl = currentUser.Figureurl.Substring(0, currentUser.Figureurl.LastIndexOf("/")) + "/100";

                            thirdID = qzone.OAuthToken.OpenId;
                            thirdNickname = currentUser.Nickname;
                            thirdUrl = currentUser.Figureurl;

                            reqLogin.OpenID = qzone.OAuthToken.OpenId;
                            break;
                        default:
                            break;
                    }

                    if (!string.IsNullOrEmpty(thirdID))
                    {
                        string userqq = string.Empty;

                        if ((RegLoginType)reqLogin.userType == RegLoginType.QQ)
                        {
                            userqq = GetUserQQByOpenID(thirdID);    //通过OpenID获取QQ号码
                        }

                        if (!string.IsNullOrEmpty(userqq))
                        {
                            thirdNickname = userqq;
                        }

                        loginResult = new LoginResult()
                        {
                            result = 0,
                            message = "登录成功",
                            type = reqLogin.userType,
                            user = thirdNickname,
                            nick = thirdNickname,
                            QQ = userqq
                        };
                    }
                }
                else
                {
                    loginResult = new LoginResult()
                    {
                        result = 2,
                        message = "请求数据错误"
                    };
                }
            }
            catch (Exception ex)
            {
                loginResult = new LoginResult()
                {
                    result = 2,
                    message = "系统繁忙，请稍后再试"
                };

                LogManager.DefaultLogger.Error(ThinkDev.Logging.LogConvert.ParseWebEx(ex), "联合登录失败");
            }

            return loginResult;
        }

        /// <summary>
        /// 获取OpenID
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetOpenID(string code)
        {
            string openID = string.Empty;

            try
            {
                QOpenClient qzone = qzone = new QOpenClient(code, string.Empty);

                if (qzone != null && qzone.OAuthToken != null)
                {
                    openID = qzone.OAuthToken.OpenId;
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, "获取OpenID失败");
            }

            return openID;
        }

        /// <summary>
        /// 通过OpenID获取QQ号码
        /// </summary>
        /// <param name="thirdID"></param>
        /// <returns></returns>
        public string GetUserQQByOpenID(string openID)
        {
            string key = string.Concat(OPENID_CACHED_KEY, ".", openID);

            string userqq = JRPTCommCache.GetCache<string>(key);

            if (string.IsNullOrEmpty(userqq))
            {
                //通过OpenID获取对应QQ
                try
                {
                    string tid = StringHelper.GetRequestTID();
                    string yidata = "{\"openid\":\"" + openID + "\",\"requestid\":\"" + tid + "\"}";

                    Encoding byteEncoder = Encoding.UTF8;
                    byte[] rijnKey = byteEncoder.GetBytes(ConfigHelper.AES_KEY);
                    byte[] rijnIV = byteEncoder.GetBytes(ConfigHelper.AES_IV);

                    string encrypted = EncryptionUtil.EncryptIt(yidata, rijnKey, rijnIV);

                    string url = string.Concat(ConfigHelper.QQUrl, "test/emUser/getUinByOpenId?yidata=", System.Web.HttpUtility.UrlEncode(encrypted));

                    //LogManager.DefaultLogger.Debug("yidata:" + yidata);
                    //LogManager.DefaultLogger.Debug("url:" + url);

                    string result = WebApiHelper.getUrl(url);

                    //LogManager.DefaultLogger.Debug("result:" + result);
                    if (!string.IsNullOrEmpty(result))
                    {
                        QQResult obj = JsonHelper.ToObject<QQResult>(result);

                        if (obj != null)
                        {
                            string temp = EncryptionUtil.DecryptIt(obj.result, rijnKey, rijnIV);

                            if (!string.IsNullOrEmpty(temp))
                            {
                                temp = temp.Replace("\0", "");

                                OpenIdQQ openIdQQ = JsonHelper.ToObject<OpenIdQQ>(temp.Trim());

                                if (openIdQQ != null && openIdQQ.code == "0" && openIdQQ.data != null)
                                {
                                    userqq = openIdQQ.data.qq;

                                    if (!string.IsNullOrEmpty(userqq))
                                    {
                                        JRPTCommCache.AddCache<string>(key, userqq);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.DefaultLogger.Error(ex, "通过OpenID获取对应QQ号码失败");
                }
            }

            return userqq;
        }

        /// <summary>
        /// 绑定QQ账号
        /// </summary>
        /// <param name="userid">用户信息表的user_id(源)</param>
        /// <param name="account">QQ号码</param>
        /// <param name="type">0:mobile; 1:email; 100:QQ</param>
        /// <param name="pwd">用户输入的密码(md5)，如果db里有密码则做校验，否则写入此密码</param>
        /// <returns></returns>
        public string BindMapUser(int userid, string account, string type, string pwd)
        {
            string ret = string.Empty;
            //string pwdMD5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5").ToLower();

            string url = string.Concat(ConfigHelper.WebAPIUrl, "/User/api/IStock.BindMapUser?appid=10001&account=",
                userid, "&toaccount=", account, "&type=", type, "&password=", pwd, "&openid=");

            try
            {
                url = WebApiHelper.CreateUrl(url);

                LogManager.DefaultLogger.Debug("url:" + url);
                string result = WebApiHelper.getUrl(url);

                if (!string.IsNullOrEmpty(result))
                {
                    WebApiJson jsonObj = JsonHelper.ToObject<WebApiJson>(result);

                    if (jsonObj != null)
                    {
                        ret = jsonObj.RetMsg;
                        //switch (jsonObj.RetCode)
                        //{
                        //    case "1":
                        //        ret = "1";
                        //        break;
                        //    case "-104200001":
                        //        switch (type)
                        //        {
                        //            case "1":
                        //                ret = "邮箱已存在";
                        //                break;
                        //            default:
                        //                ret = "手机号码已存在";
                        //                break;
                        //        }
                        //        break;
                        //    default:
                        //        if (jsonObj.RetMsg.IndexOf("|") > 1)
                        //        {
                        //            ret = jsonObj.RetMsg.Split('|')[1];
                        //        }
                        //        else
                        //        {
                        //            ret = jsonObj.Message;
                        //        }
                        //        break;
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.DefaultLogger.Error(ex, string.Concat("绑定账号失败.", userid, ".", account, ".", type, ".", pwd));
            }

            return ret;
        }
    }
}
